<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.phone"
        placeholder="手机号"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.company"
        filterable
        class="filter-item"
        clearable
        placeholder="请选择加油站"
        @keyup.enter.native="handleFilter"
      >
        <el-option
          v-for="item in cooperation"
          :label="item.company"
          :value="item.company"
        />
      </el-select>
      <!-- <el-input v-model="listQuery.title" placeholder="手机号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" /> -->

      <el-select
        v-model="listQuery.type"
        placeholder="类型"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option
          label="加油站"
          value="1"
          aria-checked=""
        />
        <!-- <el-option
          label="修理站"
          value="2"
        /> -->
        <el-option
          label="加气站"
          value="3"
        />
        <!-- <el-option
          label="总公司"
          value="4"
        /> -->
      </el-select>
      <el-select
        v-model="listQuery.state"
        placeholder="状态"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option
          label="开启"
          value="0"
          aria-checked=""
        />
        <el-option
          label="关闭"
          value="1"
        />
      </el-select>
      <!-- <el-select v-model="listQuery.type" :placeholder="$t('table.type')" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select> -->
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        {{ $t('table.search') }}
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{ $t('table.add') }}
      </el-button>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('table.export') }}
      </el-button>
      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        {{ $t('table.reviewer') }}
      </el-checkbox> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        label="序号"
        prop="id"
        align="center"
        width="50"
      >
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        label="站点名称"
        min-width="120"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.company }}
        </template>
      </el-table-column>
      <el-table-column
        label="负责人姓名"
        min-widthh="160"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column
        label="负责人电话"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>
      <el-table-column
        label="类型"
        min-width="70"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.type | typeFilter }}
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        min-width="50"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.state| stateFilter }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="优惠类型" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.author }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="优惠率" width="80" align="center">
        <template slot-scope="scope">
         {{ scope.row.author }}
        </template>
      </el-table-column> -->



    <!--  <el-table-column
        label="今日充值"
        min-width="120"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.investMoney }}
        </template>
      </el-table-column>


      <el-table-column
        label="今日消费"
        min-width="120"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.tradeMoney }}
        </template>
      </el-table-column>-->


      <!-- <el-table-column label="公司" min-width="150" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.company }}</span>
        </template>
      </el-table-column> -->

      <el-table-column
        label="地址"
        min-width="200"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.provinceName + scope.row.cityName + scope.row.areaName + scope.row.address }}
        </template>
      </el-table-column>

      <el-table-column
        v-if="isAdmin"
        prop="agentName"
        label="所属省代"
        align="center"
        width=""
      />
      <el-table-column
        v-if="isAdmin"
        prop="agentPhone"
        label="所属省代电话"
        align="center"
        width=""
      />

      <!-- <el-table-column
        label="短信接收人"
        width="105"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.receive }}
        </template>
      </el-table-column> -->

      <!-- <el-table-column
        label="创建时间"
        width="150px"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.created | parseTime('{y}-{m}-{d} {h}:{i}') }}
        </template>
      </el-table-column> -->

      <el-table-column
        label="操作"
        align="center"
        width="170px"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>

          <el-button
            type="danger"
            size="mini"
            @click="detail(scope.row)"
          >详情</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      top="2vh"
      width="720px"
    >
      <el-form
        ref="temp"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="110px"
        style="width: 550px; margin-left:50px;"
      >
        <el-form-item
          label="站点名称"
          prop="company"
        >
          <el-input v-model="temp.company" />
        </el-form-item>

        <el-form-item
          label="负责人"
          prop="name"
        >
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item
          label="电话"
          prop="phone"
        >
          <el-input
            v-model="temp.phone"
            :disabled="editPhone"
          />
        </el-form-item>


        <el-form-item
          label="类型"
          prop="type"
        >
          <el-select
            v-model="temp.type"
            class="filter-item"
          >
            <el-option
              v-for="item in typeOptions"
              :label="item.value"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="经度"
          prop="longitude"
        >
          <el-input v-model="temp.longitude" />
        </el-form-item>
        <el-form-item
          label="纬度"
          prop="latitude"
        >
          <el-input v-model="temp.latitude" />
        </el-form-item>
        <!-- <el-form-item
          label="地址"
          prop=""
        > -->
        <provinceData
          ref="provinceData"
          :temp="temp"
          @listen="getProvince"
          @ifValid="ifValid"
        />
        <!-- <el-form-item
          prop="address"
          label="详细地址"
        >
          <el-input
            v-model="temp.address"
            placeholder="详细地址"
            :value="temp.address"
          />
        </el-form-item> -->
        <!-- </el-form-item> -->

        <!--<el-form-item-->
          <!--label="公司所有人(油站主账号)电话"-->
          <!--prop=""-->
        <!--&gt;-->
          <!--<el-input v-model="temp.ownerPhone" />-->
        <!--</el-form-item>-->
        <el-form-item
          label="价格"
          prop="price"
        >
          <el-input v-model="temp.price" />
        </el-form-item>
        <!-- <el-form-item
          label="LNG价格"
          prop=""
        >
          <el-input v-model="temp.gasPrice" />
        </el-form-item> -->
        <!--<el-form-item-->
          <!--label="短信接收人"-->
          <!--prop=""-->
        <!--&gt;-->
          <!--<el-input v-model="temp.receive" />-->
        <!--</el-form-item>-->
        <el-form-item
          label="备注"
          prop=""
        >
          <el-input v-model="temp.remark" />
        </el-form-item>
        <!-- <el-form-item label="银行卡账号" prop="">
          <el-input v-model="temp.accountNo" />
        </el-form-item>
        <el-form-item label="开户人姓名" prop="">
          <el-input v-model="temp.bankAcountName" />
        </el-form-item> -->
        <el-form-item
          label="状态"
          prop="state"
        >
          <el-select
            v-model="temp.state"
            class="filter-item"
          >
            <el-option
              v-for="item in stateOptions"
              :label="item.value"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="是否启用银行卡直付功能" prop="status">
           <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
               <el-option label="开启" value="1" aria-checked=""></el-option>
               <el-option label="关闭" value="0"></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item
          v-permission="['admin']"
          label="所属代理"
          :prop="agentId"
        >
          <el-select
            v-model="temp.agentId"
            class="filter-item"
          >
            <el-option
              v-for="item in allAgent"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="createData()"
        >
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogPvVisible"
      title="Reading statistics"
    >
      <el-table
        :data="pvData"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column
          prop="key"
          label="Channel"
        />
        <el-table-column
          prop="pv"
          label="Pv"
        />
      </el-table>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="dialogPvVisible = false"
        >{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogCode"
      title="站点二维码"
      style="text-align:center"
    >
      <!-- <qrCode :codeVal="codeVal"></qrCode> -->
      <img
        :src="imageUrl"
        alt=""
      >
    </el-dialog>

  </div>
</template>

<script>
import permission from '@/directive/permission/index.js' // 权限判断指令
import checkPermission from '@/utils/permission' // 权限判断函数

import { fetchPv, updateCooperation } from '@/api/article'
import {
  cooperationList,
  createCooperation,
  editPay,
  getCode,
  getallAgent,
  cooperationAll
} from '@/api/v1'
import { cooperationUnBind } from '@/api/user'

import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import qrCode from '@/components/qrcode'
import { Loading } from 'element-ui'
import provinceData from '@/components/province'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj ,such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination, qrCode, provinceData },
  directives: { waves, permission },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      if (type == 1) {
        return '加油站'
      } else if (type == 2) {
        return '修理站'
      } else if (type == 3) {
        return '加气站'
      } else if (type == 4) {
        return '总公司'
      } else {
        return ''
      }
    },
    stateFilter(state) {
      if (state == 1) {
        return '关闭'
      } else if (state == 0) {
        return '开启'
      } else {
        return ''
      }
    }
  },
  data() {
    return {
      agentId:"agentId",
      editPhone: true,
      allAgent: [],
      imageUrl: '',
      codeVal: '',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        phone: '',
        name: '',
        type: '',
        sort: '+id',
        state: '',
        company: ''
      },
      payTypeOptions: [
        { id: 1, value: '京东支付' },
        { id: 2, value: '浦发支付' }
      ],
      stateOptions: [{ id: 0, value: '开启' }, { id: 1, value: '关闭' }],
      typeOptions: [
        { id: 1, value: '加油站' },
        // { id: 2, value: '修理站' },
        { id: 3, value: '加气站' },
        // { id: 4, value: '总公司' }
      ],
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        name: '',
        phone: '',
        id: '',
        company: '',
        type: 1,
        longitude: '',
        latitude: '',
        address: '',
        city: '',
        ownerPhone: '',
        price: '',
        remark: '',
        // gasPrice: "",
        receive: '',
        accountNo: '',
        bankAcountName: '',
        state: 0,
        status: 0,
        provinceCode: '',
        cityCode: '',
        areaCode: '',
        agentId: ''
      },
      cooperation: {},

      dialogFormVisible: false,
      dialogCode: false,
      dialogPay: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
        company: [
          { required: true, message: '请输入站点名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请至少选择一个类型', trigger: 'change' }
        ],
        longitude: [{ required: true, message: '请输入经度', trigger: 'blur' }],
        latitude: [{ required: true, message: '请输入纬度', trigger: 'blur' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
        ownerPhone: [
          {
            required: true,
            message: '请输入公司所有人(油站主账号)电话',
            trigger: 'blur'
          }
        ],
        price: [{ required: true, message: '请输入柴油价格', trigger: 'blur' }],
        remark: [
          { required: true, message: '请输入公司备注', trigger: 'blur' }
        ],
        gasPrice: [
          { required: true, message: '请输入LNG价格', trigger: 'blur' }
        ],
        receive: [
          { required: true, message: '请输入短信接收人', trigger: 'blur' }
        ],
        accountNo: [
          { required: true, message: '请输入银行卡账号', trigger: 'blur' }
        ],
        bankAcountName: [
          { required: true, message: '请输入开户人姓名', trigger: 'blur' }
        ],
        state: [
          { required: true, message: '请至少选择一个状态', trigger: 'change' }
        ],
        agentId: [
          { required: true, message: '请选择所属省代', trigger: 'change' }
        ],
        status: [
          {
            required: true,
            message: '请至少选择是否启用银行卡直付功能',
            trigger: 'change'
          }
        ]
      },
      downloadLoading: false,
      isAdmin: true,
      options: {
        fullscreen: true,
        // spinner: 'el-icon-loading',
        // background: 'rgba(0, 0, 0, 0.7)',
        text: '加载中...'
      }
    }
  },
  created() {
    this.getList()
    this.getCooperationAll()
    if (checkPermission(['admin'])) {
      this.getList2()

    }else{
       this.agentId = "";
      this.isAdmin = false
    }
  },
  methods: {
    detail(row) {
      console.log(row)
      this.$router.push({
        path: '/cooperationDetail',
        query: {
          relationId: row.id,
          relationType: 1,
          currentMoney: row.currentMoney,
          phone: row.phone,
          name: row.name,
          uuid: row.uuid
        }
      })
    },

    getList2() {
      this.listLoading = true
      getallAgent(this.listQuery).then(res => {
        this.allAgent = res.data
        console.log(this.allAgent)
      })
    },
    getProvince(data) {
      console.log('0000000000000000000000')
      console.log(data)
      this.temp.provinceCode = data.provinceCode
      this.temp.cityCode = data.cityCode
      this.temp.areaCode = data.areaCode
      this.temp.address = data.address
    },
    route(row) {
      console.log(row)
      this.$router.push({
        path: '/tradesList',
        query: {
          id: row.uuid
        }
      })
    },

    paySet(row) {
      this.pay = Object.assign({}, row) // copy obj
      console.log(row)
      this.dialogPay = true
      this.$nextTick(() => {
        this.$refs['pay'].clearValidate()
      })
      this.$refs.provinceData.clearProvinceDate()
    },
    getList() {
      this.listLoading = true
      cooperationList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = Number(response.data.total)

        // Just to simulate the time of the request
        this.listLoading = false
        //        setTimeout(() => {
        //
        //        }, 1.5 * 1000);
      })
    },
    getCooperationAll() {
      cooperationAll().then(res => {
        this.cooperation = res.data

        // Just to simulate the time of the request
        this.listLoading = false
        //        setTimeout(() => {
        //          this.listLoading = false;
        //        }, 1.5 * 1000);
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      console.log(row)
      console.log(status)
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        name: '',
        phone: '',
        id: '',
        company: '',
        type: 1,
        longitude: '',
        latitude: '',
        address: '',
        city: '',
        ownerPhone: '',
        price: '',
        remark: '',
        // gasPrice: "",
        receive: '',
        accountNo: '',
        bankAcountName: '',
        state: 0,
        status: '0',
        provinceCode: '',
        cityCode: '',
        areaCode: '',
        agentId: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      console.log(this.temp)
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.editPhone = false
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
      this.$refs.provinceData.clearProvinceDate()
    },
    ifValid(ifValid) {
      if (ifValid) {
        this.$refs['temp'].validate(valid => {
          if (valid) {
            console.log(this.temp)
            createCooperation(this.temp).then(res => {
              // this.list.unshift(this.temp);
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: res.msg,
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      }
    },
    createData() {
      this.$refs.provinceData.submitForm()
      this.$refs['temp'].validate(valid => {
        return valid
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      console.log(row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$refs.provinceData.getCityData()
      this.editPhone = true
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
      this.$refs.provinceData.clearProvinceDate()
    },

    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = [
          'timestamp',
          'title',
          'type',
          'importance',
          'status'
        ]
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>
<style>
.pagination-container {
  margin-top: 0px;
  padding-bottom: 0px !important;
}
.fixed-width .el-button--mini {
  width: 70px;
}
</style>

